package cn.gaaidou.dynamic.proxy.cglib.callback;

import cn.gaaidou.common.utils.ClazzUtil;
import cn.gaaidou.dynamic.proxy.cglib.annotation.SystemLog;
import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author Martin
 * @date 2021/7/13 19:50
 */
@Slf4j
public class SystemLogCallback implements MethodInterceptor {
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        SystemLog systemLog = method.getAnnotation(SystemLog.class);
        // 如果配置日志注解, 打印方法调用时长
        if (null != systemLog) {
            String methodName = ClazzUtil.getMethodName(method);
            long start = System.currentTimeMillis();
            log.info("方法: {} 开始执行...", methodName);
            Object o1 = methodProxy.invokeSuper(o, objects);
            long end = System.currentTimeMillis();
            log.info("方法: {} 执行完成, 耗时: {} ms", methodName, end - start);
            return o1;
        } else {
            // 没有配置日志注解的, 不走动态代理方法
            return methodProxy.invokeSuper(o, objects);
        }
    }
}
